package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description：遍历目录，看某个输入的词是否在文件名或文件内容中存在
 * User：chenshu
 * Date：2023-11-22
 * Time：09:46
 */
public class Demo9 {
    public static void checkFile(File f, String toFind) throws IOException {
        String fileName = f.getName();
        if (fileName.contains(toFind)) {
            System.out.println("找到文件名匹配的文件：" + f.getCanonicalPath());
            return;
        }
        try (InputStream inputStream = new FileInputStream(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            Scanner scanner = new Scanner(inputStream);
            while (scanner.hasNextLine()) {
                stringBuilder.append(scanner.nextLine());
            }
            if (stringBuilder.indexOf(toFind) >= 0) {
                System.out.println("找到文件内容匹配的文件：" + f.getCanonicalPath());
            }
        }
    }
    public static void scanDir(File root, String toFind) throws IOException {
        System.out.println(root.getCanonicalPath());
        File[] files = root.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                scanDir(f, toFind);
            } else {
                checkFile(f, toFind);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        System.out.println("请输入要查找的路径：");
        Scanner scanner = new Scanner(System.in);
        String rootDir = scanner.nextLine();
        File root = new File(rootDir);
        System.out.println("请输入要查找的文件名或内容：");
        String toFind = scanner.nextLine();
        scanDir(root, toFind);
    }
}
